﻿#include "textedit.h"
#include "dkd_convert.h"
#include "ui_textedit.h"
#define MAX_DICTNUM 65536

QString tmp;

QString StrReplace(QString *st1,QString *st2,int *ind,int n,QString textstr);
bool file_Edit(QString *st1,QString *st2,int *ind,int n,QString textstr);

TextEdit::TextEdit(QWidget *parent):QDialog(parent)
{
    setupUi(this);
    connect(action_Open,SIGNAL(triggered()),this,SLOT(openfile()));
    connect(actionFind,SIGNAL(triggered()),this,SLOT(findreplace()));
    connect(FindButton,SIGNAL(clicked()),this,SLOT(findtext()));
    connect(ReplaceButton,SIGNAL(clicked()),this,SLOT(replacetext()));
    connect(actionBatch_Replace,SIGNAL(triggered()),this,SLOT(batchreplace()));
    connect(BatchButton,SIGNAL(clicked()),this,SLOT(startbatch()));
    connect(BrowserButton,SIGNAL(clicked()),this,SLOT(fileBrowser()));
    connect(fileEdit,SIGNAL(textChanged(QString)),this,SLOT(setOkEndable(QString)));
    connect(actionUndo,SIGNAL(triggered()),trantext,SLOT(undo()));
    connect(actionRedo,SIGNAL(triggered()),trantext,SLOT(redo()));

    FileDock->setHidden(1);
    dockWidget->setHidden(1);
    BatchDock->setHidden(1);
    FileTable->setColumnCount(2);
    FileTable->setRowCount(20);
    FileTable->setColumnWidth(0,240);
    FileTable->setColumnWidth(1,23);
    FileTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    FileTable->setSelectionMode(QAbstractItemView::SingleSelection);
    FileTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    FileTable->horizontalHeader()->setResizeMode(QHeaderView::Fixed);
    FileTable->horizontalHeader()->setHidden(1);
    FileTable->verticalHeader()->setHidden(1);
}


bool TextEdit::newfile()
{
    return 1;
}



bool TextEdit::openfile()
{
    QString filename=QFileDialog::getOpenFileName(this,tr("Open File"),".",tr("Text Document(*.txt)"));
    QFile file(filename);
    file.open(QIODevice::ReadOnly);
    QString str=file.readAll();
    file.close();
    originaltext->setText(str);
    trantext->setText(str);
    return 1;
}

bool TextEdit::findreplace()
{
    BatchDock->setHidden(1);
    dockWidget->setHidden(0);
    return 1;
}

bool TextEdit::findreplacetext(bool i)
{
    bool b;
    QTextCursor tcursor;
    QString str=textfind->text();
    if(QString::compare(tmp,str,Qt::CaseInsensitive)!=0)
    {
        tmp=str;
        tcursor=trantext->textCursor();
        tcursor.movePosition(QTextCursor::Start);
        trantext->setTextCursor(tcursor);
    }
    b=trantext->find(str);
    tcursor=trantext->textCursor();
    if(i&b)
        tcursor.insertText(textreplace->text());
    if(!b)
        QMessageBox::warning(this,tr("Find"),tr("Can't Find %1").arg(str));
    return 1;
}

void TextEdit::findtext()
{
    findreplacetext(0);
}

void TextEdit::replacetext()
{
    findreplacetext(1);
}

bool TextEdit::batchreplace()
{
    BatchDock->setHidden(0);
    dockWidget->setHidden(1);
    fileEdit->setText("dicts/tesv.csv");
    return 1;
}

bool TextEdit::fileBrowser()
{
    QString str=QFileDialog::getOpenFileName(this,tr("Select Dictionary"),".",tr("CSV(*.csv)"));
    fileEdit->setText(str);
    return 1;
}

bool TextEdit::setOkEndable(QString str)
{
    QFileInfo file(str);
    if(!file.exists())
    {
        BatchButton->setEnabled(0);
        return 0;
    }
    BatchButton->setEnabled(1);
    return 1;
}

bool file_Edit(QString *st1,QString *st2,int *ind,int n,QString textstr)
{
    QFile file(textstr);
    file.open(QIODevice::ReadOnly);
    textstr=file.readAll();
    file.close();
    file.open(QIODevice::WriteOnly);
    textstr=StrReplace(st1,st2,ind,n,textstr);
    QTextStream out(&file);
    out<<textstr;
    file.close();
    return 1;
}

QString StrReplace(QString *st1,QString *st2,int *ind,int n,QString textstr)
{
    textstr.replace(",","，");
    textstr.replace(".","。");
    for(int i=0;i<n;++i)
        textstr.replace(st1[ind[i]],st2[ind[i]],Qt::CaseInsensitive);
    return textstr;
}

bool TextEdit::startbatch()
{
    QStringList strlist;
    QString str;
    QString *st1=new QString[MAX_DICTNUM];
    QString *st2=new QString[MAX_DICTNUM];
    int *ind,tmp;
    int n=0;
    QFile file(fileEdit->text());
    file.open(QIODevice::ReadOnly);
    while((!file.atEnd())&&n<MAX_DICTNUM)
    {
        str=file.readLine();
        strlist=str.split(",");
        st1[n]=strlist.at(0);
        st2[n]=strlist.at(1);
        ++n;
    }
    file.close();
    ind=new int[n];
    for(int i=0;i<n;++i) ind[i]=i;
    for(int i=0;i<n;++i)
        for(int j=0;j<i;++j)
        {
            if(st1[ind[j]].length()<st1[ind[i]].length())
            {
                tmp=ind[j];
                ind[j]=ind[i];
                ind[i]=tmp;
            }
        }
    if(radioButton_current->isChecked())
    {
        QString textstr=trantext->toPlainText();
        textstr=StrReplace(st1,st2,ind,n,textstr);
        trantext->clear();
        trantext->setText(textstr);
    }
    else if(radioButton_files->isChecked())
    {
        QStringList namelist,namelist1;
        QString name;
        int num,i;
        namelist=QFileDialog::getOpenFileNames(this,"Files Selection",".",tr("Text Document(*.txt)"));
        num=namelist.count();
        if(num<1)   goto LABEL_1;
        FileDock->setHidden(0);
        FileTable->clearContents();
        FileTable->setRowCount(num);
        progressBar->setValue(0);
        progressBar->setRange(0,num);
        for(i=0;i<num;++i)
        {
            name=namelist.at(i);
            namelist1=name.split("\\");
            name=namelist1.at(namelist1.count()-1);
            FileTable->setItem(i,0,new QTableWidgetItem(name));
        }
        QMessageBox::information(this,tr("Prompt"),tr("Ready"),tr("OK"));
        for(i=0;i<num;)
        {
            i+=(int)file_Edit(st1,st2,ind,n,namelist.at(i));
            progressBar->setValue(i);
        }
        QMessageBox::information(this,tr("Prompt"),tr("Complete"),tr("OK"));
    }
LABEL_1:
    delete []st1;
    delete []st2;
    delete []ind;
    return 1;
}

bool TextEdit::savefile()
{
    return 1;
}

